package com.dobbyspringside.examples.quickstart.web.account;

import com.dobbyspringside.examples.quickstart.entity.User;
import com.dobbyspringside.examples.quickstart.service.account.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

/**
 * 用户注册的controller
 * Created by liguoqing on 2016/2/17.
 */
@Controller
@RequestMapping(value = "/register")
public class RegisterController {

    @Autowired
    private AccountService accountService;


    /**
     * 注册页面
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public String registerForm(){
        return "account/register";
    }

    /**
     * 用户注册操作
     * @param user
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public String register(@Valid User user, RedirectAttributes redirectAttributes) {
        accountService.registerUser(user);
        redirectAttributes.addFlashAttribute("username",user.getLoginName());
        return "redirect:/login";
    }


    /**
     * Ajax请求校验loginName是否唯一。
     * @param loginName
     * @return
     */
    @RequestMapping(value = "checkLoginName")
    @ResponseBody
    public String checkLoginName(@RequestParam("loginName") String loginName) {
        if(accountService.findUserByLoginName(loginName) == null) {
            return "true";
        } else {
            return "false";
        }
    }

}
